package com.jtjrenren.android.taxi.passenger.core.order.status;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.jtjrenren.android.taxi.passenger.core.order.complaint.DriverComplaintActivity;
import com.jtjrenren.android.taxi.passenger.core.order.driverinfo.DriverInfoActivity;
import com.jtjrenren.android.taxi.passenger.core.order.evalution.DriverEvaluationActivity;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseMvpActivity;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiOrderDetails;
import com.jtjrenren.android.taxi.passenger.core.order.cancle.OrderCancleReasonActivity;
import com.jtjrenren.android.taxi.passenger.bean.api.CurrentOrderCost;
import com.jtjrenren.android.taxi.passenger.core.pay.main.PayActivity;
import com.jtjrenren.android.taxi.passenger.utils.InitView;
import com.jtjrenren.android.taxi.passenger.utils.UIHelper;
import com.jtjrenren.android.taxi.passenger.utils.ModuleAdapter;
import com.library.utils.LogUtil;
import com.library.weidget.CircleImageView;
import com.library.weidget.CustomFiveStars;
import com.jtjrenren.android.taxi.passenger.utils.ActivityIntentUtils;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.library.utils.StringUtils;
import com.library.utils.DensityUtils;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by Administrator on 2016/1/22.
 * 订单开始之后的状态 从司机接单开始
 */
public class OrderStatusActivity extends BaseMvpActivity<OrderStatusPresenter> implements OrderStatusView {
    public static final String EXTRA_ORDERSERNO = "orderserno";
    private static final int CODE_PAY = 200;
    private static final int CODE_PJ = 201;
    private static final int CODE_CANCLEORDER = 202;

    private static final int TIME_REFRESH_DRIVERPOS = 5000;  //刷新正在接驾中的司机的位置信息
    private static final int WHAT_REFRESH_DRIVER = 700;
    private static final int TIME_REFRESH_COST = 5000;  //刷新实时费用信息
    private static final int WHAT_REFRESH_COST = 701;

    @BindView(R.id.title)
    TextView tv_title;
    @BindView(R.id.title_right)
    TextView tv_cancle;

    //顶部相同view
    @BindView(R.id.order_status_driver_icon)
    CircleImageView driverIcon;
    @BindView(R.id.order_status_driverinfo)
    LinearLayout ll_driverinfo;
    @BindView(R.id.order_status_driver_name)
    TextView driver_name;
    @BindView(R.id.order_status_driver_carcode)
    TextView carcode;
    @BindView(R.id.order_status_driver_ordernum)
    TextView acceptNo;
    @BindView(R.id.order_status_driver_fwlevel)
    CustomFiveStars driver_level;
    @BindView(R.id.order_status_complain)
    Button bt_tousu;
    @BindView(R.id.order_status_getdriverinfo)
    TextView tv_showGetData;

    @BindView(R.id.order_status_details)
    LinearLayout ll_details;
    @BindView(R.id.order_status_details_startaddr)
    TextView tv_details_start;
    @BindView(R.id.order_status_details_endaddr)
    TextView tv_details_end;
    @BindView(R.id.order_status_details_booktime)
    TextView tv_details_book;
    @BindView(R.id.order_status_details_sfbz)
    TextView tv_details_bz;


    //司机接驾中
    @BindView(R.id.order_status_drivercoming)
    LinearLayout ll_drivercoming;
    @BindView(R.id.order_status_drivercomming_desc)
    TextView tv_driver_desc;

    //乘客上车 行驶中
    @BindView(R.id.order_status_running)
    LinearLayout ll_running;
    @BindView(R.id.order_status_running_incartime)
    TextView tv_incartime;
    @BindView(R.id.order_status_running_ssjfcon)
    LinearLayout ll_ssjf;
    @BindView(R.id.order_status_running_distance)
    TextView tv_dis;
    @BindView(R.id.order_status_running_distance_cost)
    TextView tv_discost;
    @BindView(R.id.order_status_running_timetotal)
    TextView tv_time;
    @BindView(R.id.order_status_running_time_cost)
    TextView tv_timecost;
    @BindView(R.id.order_status_running_costzs)
    TextView tv_costzs;
    @BindView(R.id.order_status_running_costxs)
    TextView tv_costxs;

    //订单结束
    @BindView(R.id.order_status_finish)
    LinearLayout ll_finished;
    @BindView(R.id.order_status_finish_costdesc)
    TextView tv_costdesc;
    @BindView(R.id.order_status_finish_pj)
    Button bt_pj;
    @BindView(R.id.order_status_finish_paynow)
    Button bt_pay;
    @BindView(R.id.order_status_finish_pjcontent)
    LinearLayout ll_pj;
    @BindView(R.id.order_status_finish_pjcontent_nr)
    TextView tv_pjnr;
    @BindView(R.id.order_status_finish_pjcontent_level)
    CustomFiveStars levelpj;
    @BindView(R.id.order_status_finish_pjcontent_leveldesc)
    TextView tv_pjleveldesc;
    @BindView(R.id.order_status_finish_xclx)
    TextView tv_xclx;
    @BindView(R.id.order_status_pay_desc)
    TextView tv_pay_desc;
    @BindView(R.id.order_status_finish_costcon)
    LinearLayout ll_cost_con;

    //专车费用明细
    @BindView(R.id.order_status_finish_specar)
    RelativeLayout rl_specar;
    @BindView(R.id.order_status_finish_specar_zk)
    TextView tv_zk;
    @BindView(R.id.order_status_finish_specar_sq)
    ImageView iv_sq;
    @BindView(R.id.order_status_finish_specar_costdetails)
    LinearLayout ll_costdetails;

    //订单关闭 取消或者其他原因
    @BindView(R.id.order_status_closed)
    LinearLayout ll_closed;
    @BindView(R.id.order_status_closed_reason)
    TextView tv_reasonc;
    @BindView(R.id.order_status_closed_desc)
    TextView tv_reason_title;

    @BindView(R.id.order_status_map)
    MapView bdMapView;

    private BitmapDescriptor startMarkerDes = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_tag_start);
    private BitmapDescriptor endMarkerDes = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_tag_end);
    private BitmapDescriptor locMarkerDes = BitmapDescriptorFactory
            .fromResource(R.mipmap.def_postion_orange);
    private BitmapDescriptor driverMarkerDes = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_taxi_marker);

    private OverlayOptions startOption, endOption, currentOption;

    private BaiduMap bdMap;

    public static Intent getDiyIntent(Context context, String orderID) {
        Intent intent = new Intent(context, OrderStatusActivity.class);
        intent.putExtra(EXTRA_ORDERSERNO, orderID);
        return intent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.destory();
        startMarkerDes.recycle();
        endMarkerDes.recycle();
        locMarkerDes.recycle();
        driverMarkerDes.recycle();

        if (handler!=null) {
            handler.removeMessages(WHAT_REFRESH_COST);
            handler.removeMessages(WHAT_REFRESH_DRIVER);
        }
        LogUtil.log("debug", "订单状态界面销毁");
    }

    @Override
    public int getLayoutId() {
        return R.layout.aty_order_stauts;
    }

    @Override
    public OrderStatusPresenter createPresenter() {
        return new OrderStatusPresenterImpl(this);
    }

    @Override
    public void initM() {
        LogUtil.log("debug", "状态界面初始化");

        bdMap = bdMapView.getMap();
        InitView.initBdmapView(bdMapView);

        initHandler();
        presenter.init();
        presenter.initOrder(getIntent().getStringExtra(EXTRA_ORDERSERNO));
    }

    @Override
    public void refreshMapCenter(LatLng target) {
        MapStatus.Builder builder = new MapStatus.Builder().target(target).zoom(17);
        MapStatusUpdate update = MapStatusUpdateFactory.newMapStatus(builder.build());
        bdMap.animateMapStatus(update);
    }

    @Override
    public void refreshSpecarView() {
        bt_pay.setText("立即支付");
        tv_details_bz.setVisibility(View.VISIBLE);
    }

    @Override
    public void refreshTaxiView() {
        bt_pay.setText("立即支付");
        tv_details_bz.setVisibility(View.GONE);
    }

    @Override
    public void showCommon(ApiOrderDetails.MsgEntity info) {
        if (info == null)
            return;

        LogUtil.log("debug", this.toString() + "====details==null-->" + (ll_details == null));
        ll_details.setVisibility(View.VISIBLE);
        tv_showGetData.setVisibility(View.GONE);
        ll_driverinfo.setVisibility(View.VISIBLE);

        ImageLoader.getInstance().displayImage(info.getHeadImg(), driverIcon, InitView.getDisplayOptions());
        driver_name.setText(info.getDriverName());
        carcode.setText(info.getCarNum());
        acceptNo.setText(info.getSuccess());
        driver_level.show(Integer.parseInt(info.getServiceLevel()));

        tv_details_start.setText(info.getStartAddr());
        tv_details_end.setText(info.getEndAddr());
        tv_details_book.setText(info.getCreateDate());


        if (!StringUtils.isEmpty(info.getStartLat()) && !StringUtils.isEmpty(info.getStartLng())) {
            LatLng startLL = new LatLng(Double.parseDouble(info.getStartLat()), Double.parseDouble(info.getStartLng()));
            LatLng endLL = new LatLng(Double.parseDouble(info.getEndLat()), Double.parseDouble(info.getEndLng()));
            startOption = new MarkerOptions()
                    .position(startLL)
                    .icon(startMarkerDes);
            endOption = new MarkerOptions()
                    .position(endLL)
                    .icon(endMarkerDes);
            showMarkerSpan(startLL, startOption, endOption);
        }

        if (Integer.parseInt(info.getOrderType()) == Constants.CARTYPE_SPECAR) {
            driverMarkerDes = BitmapDescriptorFactory
                    .fromResource(R.mipmap.icon_specar_marker);
        }
    }

    @Override
    public void clearStatusView() {
        tv_title.setText(getString(R.string.app_name));
        tv_cancle.setVisibility(View.GONE);

        ll_drivercoming.setVisibility(View.GONE);

        ll_closed.setVisibility(View.GONE);
        ll_running.setVisibility(View.GONE);
        ll_finished.setVisibility(View.GONE);

        tv_xclx.setVisibility(View.GONE);

        handler.removeMessages(WHAT_REFRESH_DRIVER);
        handler.removeMessages(WHAT_REFRESH_COST);

        presenter.clearStatus();
    }

    @Override
    public void showOrderNotStart() {
        tv_title.setText("未开始");
        tv_cancle.setVisibility(View.VISIBLE);
    }

    @Override
    public void showDriverComing() {
        ll_drivercoming.setVisibility(View.VISIBLE);
        tv_cancle.setVisibility(View.VISIBLE);
        tv_title.setText(R.string.jiejiazhong);

        //展示司机位置跟我的位置
        handler.sendEmptyMessage(WHAT_REFRESH_DRIVER);
    }

    @Override
    public void startGetDriverPostion() {
        handler.sendEmptyMessage(WHAT_REFRESH_DRIVER);
    }

    @Override
    public void showInCar(ApiOrderDetails.MsgEntity info) {
        ll_running.setVisibility(View.VISIBLE);
        tv_title.setText(R.string.xingshizhong);

        //展示终点位置跟当前位置
        currentOption = endOption;
    }

    @Override
    public void showInCarSpecar() {
        ll_ssjf.setVisibility(View.VISIBLE);
    }

    @Override
    public void startGetCost() {
        handler.removeMessages(WHAT_REFRESH_COST);
        handler.sendEmptyMessage(WHAT_REFRESH_COST);
    }

    @Override
    public void showInCarTaxi() {
        ll_ssjf.setVisibility(View.GONE);
    }

    @Override
    public void refreshRunDetails(CurrentOrderCost.DataListEntity entity) {
        if (entity == null)
            return;
        tv_incartime.setText(entity.getStartOrderTime());
        tv_dis.setText(entity.getDistance() + "");
        tv_discost.setText(entity.getDistanceMoney() + "");
        tv_time.setText(entity.getTimeLong() + "");
        tv_timecost.setText(entity.getTimeLongMoney() + "");
        String[] costDetails = ModuleUtils.getCostDetails(entity.getTotalMoney() + "");
        tv_costzs.setText(costDetails[0]);
        tv_costxs.setText(costDetails[1]);
    }

    @Override
    public void showFinishView(ApiOrderDetails.MsgEntity info) {
        tv_xclx.setVisibility(View.VISIBLE);
        ll_finished.setVisibility(View.VISIBLE);
        tv_title.setText(R.string.dingdanwancheng);
        bdMapView.setVisibility(View.GONE);
    }

    @Override
    public void refreshOrderCost(boolean isShow, String desc) {
        if (isShow) {
            ll_cost_con.setVisibility(View.VISIBLE);
            tv_costdesc.setText(desc);
        } else
            ll_cost_con.setVisibility(View.GONE);
    }

    @Override
    public void refreshPjView(boolean isPj) {
        if (isPj) {
            bt_pj.setVisibility(View.VISIBLE);
        } else {
            bt_pj.setVisibility(View.GONE);
        }
    }

    @Override
    public void refershPayView(boolean isPay, String desc) {
        tv_pay_desc.setText(desc);
        if (!isPay) {
            bt_pay.setVisibility(View.VISIBLE);
        } else {
            bt_pay.setVisibility(View.GONE);
        }
    }

    @Override
    public void refreshSpecarCostView(boolean isShow) {
        if (isShow)
            rl_specar.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCloseView(String closeRaeson) {
        clearStatusView();
        ll_closed.setVisibility(View.VISIBLE);
        tv_title.setText(R.string.dingdanguanbi);
        tv_reasonc.setText(closeRaeson);
        bdMapView.setVisibility(View.GONE);


        //展示起点跟终点的位置
        showMarkerSpan(null, startOption, endOption);
    }

    @Override
    public void showPjContent(int level, String content) {
        ll_pj.setVisibility(View.VISIBLE);
        tv_pjnr.setText(StringUtils.isEmpty(content) ? "" : content);
        levelpj.show(level);
        tv_pjleveldesc.setText(ModuleAdapter.getLevelDesc(level));
    }

    @Override
    public void showTsView(boolean isShow) {
        if (isShow)
            bt_tousu.setVisibility(View.VISIBLE);
        else
            bt_tousu.setVisibility(View.GONE);
    }

    @Override
    public void refershDriverPostion(LatLng postion, String desc) {
        currentOption = new MarkerOptions()
                .position(postion)
                .icon(driverMarkerDes);

        showMarkerSpan(postion, currentOption);

        tv_driver_desc.setText(desc);
    }

    @Override
    public void refreshLocMark(LatLng loc) {
        OverlayOptions loco = new MarkerOptions()
                .position(loc)
                .icon(locMarkerDes);

        showMarkerSpan(loc, loco, currentOption);
    }

    @Override
    public void goPayPage(String orderID) {
        startActivityForResult(PayActivity.getDiyIntent(OrderStatusActivity.this, orderID), CODE_PAY);
    }

    @Override
    public void showTip(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showWaittingView(String desc) {
        showWaittingDialog(desc, false);
    }

    @Override
    public void dissWaittingView() {
        dismissWaittingDialog();
    }

    @OnClick(R.id.title_left)
    public void clickBack() {
        finish();
    }

    @OnClick(R.id.title_right)
    public void clickCancle() {
        Intent intent = new Intent(OrderStatusActivity.this, OrderCancleReasonActivity.class);
        startActivityForResult(intent, CODE_CANCLEORDER);
    }

    @OnClick(R.id.order_status_details_sfbz)
    public void clickSfbz() {
        ActivityIntentUtils.showHtmlActivity(this, presenter.getSfbzUrl(), "收费标准", true);
    }

    @OnClick(R.id.order_status_call_driver)
    public void clickCallDriver() {
        UIHelper.showCallDialog(this, presenter.getDriverPhone());
    }

    @OnClick(R.id.order_status_call_kf)
    public void clickCallKf() {
        UIHelper.showCallDialog(this, getString(R.string.phone_custome));
    }

    @OnClick(R.id.order_status_complain)
    public void clickComplain() {
        Intent intent = new Intent(OrderStatusActivity.this, DriverComplaintActivity.class);
        intent.putExtra(DriverComplaintActivity.EXTRAS_ORDERNO, presenter.getOrderID());
        intent.putExtra(DriverComplaintActivity.EXTRAS_DRIVERID, presenter.getDriverID());
        startActivity(intent);
    }

    @OnClick(R.id.order_status_driver_icon)
    public void clickShowDriver() {
        LogUtil.log("debug", "司机id：" + presenter.getDriverID());
        startActivity(DriverInfoActivity.getDiyIntent(this, presenter.getDriverID()));
    }


    @OnClick(R.id.specar_orderstatus_comming_bt_cancle)
    public void clickCancleRungin() {
        Intent intent = new Intent(OrderStatusActivity.this, OrderCancleReasonActivity.class);
        startActivityForResult(intent, CODE_CANCLEORDER);
    }

    @OnClick(R.id.specar_orderstatus_comming_bt_calldriver)
    public void clickDriver() {
        UIHelper.showCallDialog(this, presenter.getDriverPhone());
    }

    @OnClick(R.id.order_status_finish_pj)
    public void clickPJ() {
        Intent intent = new Intent(OrderStatusActivity.this, DriverEvaluationActivity.class);
        intent.putExtra(DriverEvaluationActivity.EXTRAS_ORDERID, presenter.getOrderID());
        intent.putExtra(DriverEvaluationActivity.EXTRAS_DRIVERID, presenter.getDriverID());
        startActivityForResult(intent, CODE_PJ);
    }

    @OnClick(R.id.order_status_finish_paynow)
    public void clickPay() {
        presenter.pay();
    }

    @OnClick(R.id.order_status_finish_xclx)
    public void clickXcgj() {
        ActivityIntentUtils.showHtmlActivity(this, presenter.getXcgjUrl(), "行车轨迹", true);
    }

    @OnClick(R.id.order_status_finish_specar_sq)
    public void clickSq() {
        tv_zk.setVisibility(View.VISIBLE);
        ll_costdetails.setVisibility(View.GONE);
        iv_sq.setVisibility(View.GONE);
    }

    @OnClick(R.id.order_status_finish_specar_zk)
    public void clickZk() {
        tv_zk.setVisibility(View.GONE);
        ll_costdetails.setVisibility(View.VISIBLE);
        iv_sq.setVisibility(View.VISIBLE);
        showEstimatedCost(presenter.getCostDesc());
    }


    @Override
    protected void handMsg(Message msg) {
        super.handMsg(msg);
        switch (msg.what) {
            case WHAT_REFRESH_DRIVER:
                handler.removeMessages(WHAT_REFRESH_DRIVER);
                presenter.getDriverPostion();
                handler.sendEmptyMessageDelayed(WHAT_REFRESH_DRIVER, TIME_REFRESH_DRIVERPOS);
                break;
            case WHAT_REFRESH_COST:
                handler.removeMessages(WHAT_REFRESH_COST);
                presenter.getCostSpecar();
                handler.sendEmptyMessageDelayed(WHAT_REFRESH_COST, TIME_REFRESH_COST);
                break;
        }
    }


    private void showMarkerSpan(LatLng target, OverlayOptions... options) {
        bdMap.clear();
        for (OverlayOptions option : options)
            bdMap.addOverlay(option);
        if (target != null)
            refreshMapCenter(target);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_PAY && resultCode == RESULT_OK)
            refershPayView(true, "已支付");
        if (requestCode == CODE_PJ && resultCode == RESULT_OK) {
            refreshPjView(false);
            String content = data.getStringExtra(DriverEvaluationActivity.RESULT_PJ);
            int level = data.getIntExtra(DriverEvaluationActivity.RESULT_PJ_LEVEL, 2);
            level = ModuleAdapter.changeevServiceLevelToLocL(level);
            LogUtil.log("order", "评价结果：" + level);
            showPjContent(level, content);
        }
        if (requestCode == CODE_CANCLEORDER && resultCode == RESULT_OK) {
            int reason = 0;
            reason = data.getIntExtra(OrderCancleReasonActivity.RESULT_DATA, 0);
            presenter.cancleOrder(reason);
        }
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    private void showEstimatedCost(String str) {
        if (StringUtils.isEmpty(str))
            return;

        ll_costdetails.removeAllViews();

        // 小费总是放在最后一个
        String[] lines = str.split("&");
        String[] contens;
        int lineLen = lines.length;

        if (lineLen < 1)
            return;

        if (lines[lineLen - 1].length() < 3) {
            lineLen = lineLen - 1;
        }


        LayoutParams container_params = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        container_params.gravity = Gravity.CENTER_VERTICAL;
        LayoutParams label_params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.MATCH_PARENT);
        label_params.weight = 1;

        LinearLayout ll_container;
        TextView tv_desc, tv_content;
        int padding = DensityUtils.dip2px(this, 3);

        for (int i = 0; i < lineLen; i++) {
            if (StringUtils.isEmpty(lines[i]))
                continue;

            contens = lines[i].split("\\|");
            if (contens.length < 2)
                continue;


            ll_container = new LinearLayout(this);
            ll_container.setLayoutParams(container_params);
            ll_container.setOrientation(LinearLayout.HORIZONTAL);
            ll_container.setPadding(0, padding, 0, padding);

            tv_desc = new TextView(this);
            tv_desc.setLayoutParams(label_params);
            tv_desc.setGravity(Gravity.LEFT);
            tv_desc.setTextSize(14);
            tv_desc.setTextColor(getResources().getColor(
                    R.color.label_show_extrude));

            tv_content = new TextView(this);
            tv_content.setLayoutParams(label_params);
            tv_content.setGravity(Gravity.RIGHT);
            tv_content.setTextSize(14);
            tv_content.setTextColor(getResources().getColor(
                    R.color.label_show_extrude));
//            tv_content.setTextColor(getResources().getColor(
//                    R.color.label_normal));


            tv_desc.setText(contens[0]);
            tv_content.setText(contens[1]);
            ll_container.addView(tv_desc);
            ll_container.addView(tv_content);

            ll_costdetails.addView(ll_container);
        }
    }


}
